{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7d6554e463fdd57d",
   "metadata": {},
   "source": "# FOR DEEP LEARNING OF https://zh.d2l.ai/ (branch 2.3-)"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "> AUTHOR: **2864** IN TJU CHINA  \n",
    "> DATE: 9 / 23 / 2024"
   ],
   "id": "a6aee7d913bf4ec6"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "***\n",
    "### 2.3 Linear Algebra"
   ],
   "id": "29ddb46800ba0704"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "默认情况下，调用求和函数 **tf.reduce_sum()** 会沿所有的轴降低张量的维度，使它变为一个标量。",
   "id": "71e1b129173114dd"
  },
  {
   "cell_type": "code",
   "id": "ee3bdf64-74ce-474e-9612-db2b878b0814",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-23T11:54:17.730472Z",
     "start_time": "2024-09-23T11:54:17.723241Z"
    }
   },
   "source": [
    "import tensorflow as tf\n",
    "A = tf.reshape(tf.range(20,dtype = tf.float32),(5,4))\n",
    "print(A)\n",
    "print(tf.reduce_sum(A))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tf.Tensor(\n",
      "[[ 0.  1.  2.  3.]\n",
      " [ 4.  5.  6.  7.]\n",
      " [ 8.  9. 10. 11.]\n",
      " [12. 13. 14. 15.]\n",
      " [16. 17. 18. 19.]], shape=(5, 4), dtype=float32)\n",
      "tf.Tensor(190.0, shape=(), dtype=float32)\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "",
   "id": "27238d6ff10b7f6c"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "调用求和函数会沿所有的轴降低张量的维度，使它变为一个 **标量** 。 我们可以指定张量沿哪一个轴来通过求和降低维度。  \n",
    "以矩阵为例，为了通过求和所有**行**的元素来降维（轴0），可以在调用函数时指定 **axis=0**。  \n",
    "指定 **axis=1** 将通过汇总所有**列**的元素降维（轴1）。"
   ],
   "id": "4f64adfd7ee99af"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-23T11:54:20.179684Z",
     "start_time": "2024-09-23T11:54:20.175981Z"
    }
   },
   "cell_type": "code",
   "source": [
    "A_sum_axis0 = tf.reduce_sum(A, axis=0)\n",
    "print(A_sum_axis0)\n",
    "A_sum_axis1 = tf.reduce_sum(A, axis=1)\n",
    "print(A_sum_axis1)"
   ],
   "id": "8525bcd02d0319a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tf.Tensor([40. 45. 50. 55.], shape=(4,), dtype=float32)\n",
      "tf.Tensor([ 6. 22. 38. 54. 70.], shape=(5,), dtype=float32)\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "在代码中，我们可以调用函数 **tf.reduce_mean()** 来计算任意形状张量的平均值。",
   "id": "79d3c21c01770625"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-23T11:54:29.791100Z",
     "start_time": "2024-09-23T11:54:29.785579Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(tf.reduce_mean(A))\n",
    "print(tf.reduce_sum(A, axis=0) / A.shape[0]) #逐列均值  "
   ],
   "id": "b91834bdbb4705a1",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tf.Tensor(9.5, shape=(), dtype=float32)\n",
      "tf.Tensor([ 8.  9. 10. 11.], shape=(4,), dtype=float32)\n"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "另外，非降维求和参数 **keepdims=True** 可以保持张量的维数  \n",
    "我们可以通过广播机制计算标量元素占比"
   ],
   "id": "606a7352a6e7118f"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-23T11:56:28.020926Z",
     "start_time": "2024-09-23T11:56:28.016690Z"
    }
   },
   "cell_type": "code",
   "source": [
    "sum_A = tf.reduce_sum(A, axis=1, keepdims=True)\n",
    "#print(sum_A)\n",
    "print(A / sum_A)"
   ],
   "id": "113da673b26252a2",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tf.Tensor(\n",
      "[[0.         0.16666667 0.33333334 0.5       ]\n",
      " [0.18181819 0.22727273 0.27272728 0.3181818 ]\n",
      " [0.21052632 0.23684211 0.2631579  0.28947368]\n",
      " [0.22222222 0.24074075 0.25925925 0.2777778 ]\n",
      " [0.22857143 0.24285714 0.25714287 0.27142859]], shape=(5, 4), dtype=float32)\n"
     ]
    }
   ],
   "execution_count": 18
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "如果我们想沿某个轴计算A元素的累积总和， 比如axis=0（按行计算），可以调用 **tf.cumsum()** 函数。  \n",
    "此函数不会沿任何轴降低输入张量的维度。"
   ],
   "id": "d024cec7eb750cc0"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-23T11:58:48.529441Z",
     "start_time": "2024-09-23T11:58:48.522975Z"
    }
   },
   "cell_type": "code",
   "source": "print(tf.cumsum(A, axis=0))",
   "id": "799830e2ebeba456",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tf.Tensor(\n",
      "[[ 0.  1.  2.  3.]\n",
      " [ 4.  6.  8. 10.]\n",
      " [12. 15. 18. 21.]\n",
      " [24. 28. 32. 36.]\n",
      " [40. 45. 50. 55.]], shape=(5, 4), dtype=float32)\n"
     ]
    }
   ],
   "execution_count": 19
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "87132f395fc429e4"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
